<template>
  <div class="about" >
    <el-table :data="mydata" border stripe>
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="选择" width="50">
        <template #default="scope">
          <el-checkbox v-model="scope.row.check" />
      </template>
      </el-table-column>
      <el-table-column label="选择2" width="50">
        <template #default="scope">
          <el-checkbox v-model="scope.row.check2" />
      </template>
      </el-table-column>
    </el-table>
    <h1>AI测试案例(暂不支持上下文)</h1>
    <span>这里的输入是定义AI人设，并非聊天机器人，AI会根据对其定义的人设生成相应的回复。如你可以定义：“你叫小威，今年28岁，是一位可爱的女孩子，你的回复是开心的，并且喜欢说笑话”</span>
    <el-input v-model="question" placeholder="请输入定义"></el-input>
    <div class="aiBox" v-for="(item,index) in aiResponse" :key="index" >
      <vue-markdown-it class="aiContent" :source="item.response" :options="options" preset="commonmark"/>
      <div class="aiQuestion">问题：{{item.question}}</div>
    </div>
    <el-button @click="sendQuestion" type="primary" v-loading="intId != null">发送</el-button>
    <el-button @click="clearInt" type="primary">停止生成内容</el-button>
    <h1>元素拖拽案例</h1>
    <div v-mov="{title:true,position:'click',overflow:'auto'}" class="drag-box">
      <div class="title">标题（拖拽区域）</div>
      <div class="content">内容</div>
    </div>

    <h1>图片懒加载案例</h1>
    <img v-imgLazy="'https://tupian.qqw21.com/article/UploadPic/2022-3/202233017485161773.jpg'" v-for="i in 10" :key="i" width="150px" height="150px" style="display:block;">
  </div>
</template>
<script setup>
import { reactive, watch, ref, onMounted } from 'vue';
import axios from 'axios';
import { VueMarkdownIt } from '@f3ve/vue-markdown-it';
// AI测试
import { Client } from "@gradio/client";

let aiResponse = ref([])
let question = ref('')
let intId = ref(null)

const clearInt = () => {
  clearInterval(intId.value)
  intId.value = null
}

const options = {
  html: true,
  linkify: true,
};

const sendQuestion = () => {
  if(question.value.trim() == '') return
  intId.value = 1
  // Ollama服务请求，可以正常使用
  // 具体文档参考https://github.com/ollama/ollama/blob/main/docs/api.md#request-json-mode
  axios.post('http://localhost:11434/api/generate',{
  "model": "mistral",
  "prompt":question.value
 }).then(res=>{
    // 加入p标签，表示下一段回复及提问内容
    // aiResponse.value += '#### 问题：'+ question.value + '   \n'
    // aiResponse.value += 'AI回复：'
    
    // 将AI返回的内容解析成数组对象
    let wordList ='['+ res.data.replace(/(?<=})\s*\{/g, ',{').slice(0, -1) +']'
    let dataArr = JSON.parse(wordList)
    // 速度太快，换成计时器更有感觉
    // for (const word in dataArr) {
    //   aiResponse.value += dataArr[word].response
    // }
    // 通过计时器实现逐个字符输出
    let idx = 1
    let length = aiResponse.value.push({ //如果要让数据向上推使用unshift
      question: question.value,
      response: dataArr[0].response
    })
    intId.value = setInterval(()=>{
      if(idx < dataArr.length){
        idx++
        // 配合unshift修改成 aiResponse.value[0].response += dataArr[idx-1].response 即可
        aiResponse.value[length-1].response += dataArr[idx-1].response
      }else{
        idx = 1
        clearInterval(intId.value)
        intId.value = null
      }
    },50)
    // 清空输入框
    question.value = ''
  }).catch(err=>{
    console.log(err)
    intId.value = null
  })
}


onMounted(async ()=>{
// privateGPT测试用接口（无法正常使用）
//   const app = await Client.connect("http://localhost:8001/");
//   const result = await app.predict("/chat", [		
//       "1", // string  in 'Message' Textbox component		
//       "2", // string  in 'Mode' Radio component		
//       "4", //   in 'Upload File(s)' Uploadbutton component		
//       null, // string  in 'System Prompt' Textbox component
//       "3" // string  in 'System Prompt' Textbox component
//   ]);
//   console.log(result.data);
})




let mydata = reactive([
  {id:1,check:true,check2:false},
  {id:2,check:false,check2:true},
  {id:3,check:true,check2:true},
  {id:4,check:false,check2:false},
])

// 假设check代表要获取的第一列多选id，check2代表要获取的第二列多选id
let result1 = ref([])
let result2 = ref([])

watch(mydata,(oldval,newval)=>{
  let id1 = []
  let id2 = []
  id1 = mydata.filter((currentValue,index,arr)=>{
    return currentValue.check == true
  })
  id2 = mydata.filter((currentValue,index,arr)=>{
    return currentValue.check2 == true
  })
  result1.value = id1.map((i)=>{return i.id})
  result2.value = id2.map((i)=>{return i.id})

  console.log('选中第一列的id：'+result1.value,'选中第二列的id：'+result2.value)
},{deep:true,immediate:true})
</script>
<style lang="scss" scoped>
pre{
  padding-left:10px;
  color:white;
  background-color: #000;
}
.aiBox{
  margin-bottom:10px;
  width:500px;
  border:1px solid #ccc;
  box-shadow: 0 0 10px #ccc;
  border-radius: 5px;
  .aiQuestion{
    color:#666;
    margin:10px;
    padding:5px;
    text-align:right;
  }
  .aiContent{
      color:#666;
      margin:10px;
      background-color:#ccc;
      padding:5px;
  }
}

.drag-box{
  width:400px;
  height:400px;
  color:#000;
  border:1px solid #ccc;
  background-color: #fff;
  box-shadow: 0 0 10px #ccc;
  .title{
    background: #000;
    color:white;
    padding:5px;
  }
  .content{
    padding: 5px;
  }
}
</style>
